package logic

import (
	"baidu/baidurpc/baidurpc"
	"baidu/baidurpc/internal/svc"
	"baidu/modil/cache"
	"baidu/modil/mysql"
	"context"
	"github.com/zeromicro/go-zero/core/jsonx"
	"time"

	"github.com/zeromicro/go-zero/core/logx"
)

type LikeListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLikeListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LikeListLogic {
	return &LikeListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *LikeListLogic) LikeList(in *baidurpc.LikeListRequest) (*baidurpc.LikeListResponse, error) {
	// todo: add your logic here and delete this line
	var book []mysql.Book
	get, _ := cache.Rdb.Get(l.ctx, "LikeList").Result()
	if get != "" {
		jsonx.Unmarshal([]byte(get), &book)
	} else {
		mysql.DB.Debug().Find(&book)
		marshal, _ := jsonx.Marshal(book)
		cache.Rdb.Set(l.ctx, "LikeList", marshal, time.Minute*5)
	}
	var likesList []*baidurpc.LikeList
	for _, m := range book {
		list := baidurpc.LikeList{
			Title:  m.Title,
			Text:   m.Text,
			UserId: m.UserId,
			Types:  m.Types,
			Likes:  int64(m.Likes),
		}
		likesList = append(likesList, &list)
	}
	mysql.DB.Debug().Find(&likesList)
	return &baidurpc.LikeListResponse{
		List: likesList,
	}, nil
}
